﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net.Security;
using System.Net;
using System.Security.Cryptography.X509Certificates;
using System.Text;

namespace zUfDsl.Common
{

    /// <summary>
    /// Http连接对象
    /// </summary>
    public class HandleHttp:IDisposable
    {
        HttpWebRequest _request;
        HttpWebResponse _response = null;
        private string _url;
        /// <summary>
        /// Http连接对象
        /// </summary>
        public HandleHttp(string url,bool addUserCookie)
        {
            System.GC.Collect();
            _url = url;
            //设置最大连接数
            ServicePointManager.DefaultConnectionLimit = 200;
            //设置https验证方式
            if (url.StartsWith("https", StringComparison.OrdinalIgnoreCase))
            {
                ServicePointManager.ServerCertificateValidationCallback =
                        new RemoteCertificateValidationCallback(CheckValidationResult);
            }
            _request = WebRequest.Create(url) as HttpWebRequest;
            if(addUserCookie)
            {
                CookieContainer cookieContainer = new CookieContainer();
                var cookie = new Cookie("userName", cHandleUF.cUserName,"/" , GetDomain(url));
                cookieContainer.Add(cookie);
                _request.CookieContainer = cookieContainer;
            }
        }
        /// <summary>
        /// 获取域名
        /// </summary>
        private string GetDomain(string urlori)
        {
            var patter = "https?://.+?/";
            var match = new System.Text.RegularExpressions.Regex(patter);
            var result = match.Match(urlori);
            var alldomain = "";
            if (result.Success == false)
            {
                alldomain = urlori;
            }
            else
            {
                alldomain = result.Value;
            }
            alldomain = alldomain.Trim('/');
            var lastindex = alldomain.LastIndexOf("/");
            if (lastindex > 0)
            {
                var rval = alldomain.Substring(lastindex + 1, alldomain.Length - lastindex - 1);
                return rval;
            }
            else { return alldomain; }
        }

        #region 通用Get方法，可以处理http与https，返回数据，返回String
        /// <summary>
        /// 通用Get方法，可以处理http与https，返回数据，返回String
        /// </summary>
        public string Get()
        {
            _request.Method = "GET";
            //获取服务器返回
            _response = (HttpWebResponse)_request.GetResponse();
            //获取HTTP返回数据
            StreamReader sr = new StreamReader(_response.GetResponseStream(), Encoding.UTF8);
            var result = sr.ReadToEnd().Trim();
            sr.Close();
            return result;
        }
        #endregion

        #region https Get方式访问必须返回证书认证正确
        private bool CheckValidationResult(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors errors)
        {
            //直接确认，否则打不开
            return true;
        }
        #endregion
        

        #region 通用Post方法,http与https一致字符串
        /// <summary>
        /// 通用Post方法,http与https一致字符串
        /// </summary>
        public string Post<T>(T obj)
        {
            var s = Common.HandleJSON.Serialize(obj);
            return Post(s);
        }
        #endregion

        #region 通用Post方法,http与https一致字符串
        /// <summary>
        /// 通用Post方法,http与https一致字符串
        /// </summary>
        public string Post(string post)
        {            
            byte[] data = Encoding.UTF8.GetBytes(post);

            _request.Timeout = 10000000;

            _request.AllowAutoRedirect = true;
            _request.Method = "POST";
            _request.ContentType = "application/json";
            _request.ContentLength = data.Length;
            var outstream = _request.GetRequestStream();
            outstream.Write(data, 0, data.Length);
            outstream.Close();
            _response = _request.GetResponse() as HttpWebResponse;
            var instream = _response.GetResponseStream();
            var sr = new StreamReader(instream, Encoding.UTF8);
            string content = sr.ReadToEnd();
            return content;
        }

        public void Dispose()
        {
            #region  关闭连接和流
            if (_response != null)
            {
                _response.Close();
            }
            if (_request != null)
            {
                _request.Abort();
            }
            #endregion
        }
        #endregion

    }
}

